/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.eric.server.monitor;

import com.eric.server.packet.PacketDecoder;
import com.eric.server.packet.PacketEncoder;
import com.eric.server.utils.SystemUtils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetAddress;


public final class MonitorServer extends Thread{
    MonitorListener listener ;
    ChannelFuture channelFuture ;
    int port ;

    public MonitorServer(MonitorListener listener){
        this.listener = listener;
    }

    public void startServer(int port) throws Exception {
        this.port = port;
        start();
    }

    public void run() {
        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>(){
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new PacketDecoder(1024*1, 4,4,0,0));
                            pipeline.addLast(new PacketEncoder());
                            pipeline.addLast(new MonitorHandler());
                        }
                    });

            // Start the server.
            channelFuture = bootstrap.bind(port).sync();
            System.out.println(" >>  started  << ");
            if(listener != null){
                listener.started(SystemUtils.getLocalHost(),port);
            }
            // Wait until the server socket is closed.
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            if(listener != null){
                listener.stoped();
            }
        }
    }

    public void stopServer(){
        channelFuture.channel().close();
    }

}
